<template>
  <div class="cloud-drive-container">
    <!-- 顶部工具栏 -->
    <div class="toolbar">
      <div class="toolbar-left">
        <el-button type="primary" @click="handleUpload" :icon="Upload">
          上传文件
        </el-button>
        <el-button @click="handleCreateFolder" :icon="FolderAdd">
          新建文件夹
        </el-button>
        <el-button @click="handleRefresh" :icon="Refresh">
          刷新
        </el-button>
      </div>
      
      <div class="toolbar-right">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索文件或文件夹"
          :prefix-icon="Search"
          style="width: 300px"
          @keyup.enter="handleSearch"
          clearable
        />
        <el-button @click="handleSearch" :icon="Search" type="primary">
          搜索
        </el-button>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 左侧文件夹树 -->
      <div class="sidebar">
        <div class="sidebar-header">
          <h3>文件夹</h3>
          <el-button 
            type="text" 
            @click="toggleSidebar"
            :icon="sidebarCollapsed ? ArrowRight : ArrowLeft"
          />
        </div>
        
        <div class="sidebar-content" v-show="!sidebarCollapsed">
          <FolderTree
            :folders="folderTree"
            :current-folder-id="currentFolderIdSafe"
            @folder-select="handleFolderSelect"
            @folder-context-menu="handleFolderContextMenu"
          />
        </div>
      </div>

      <!-- 右侧文件列表 -->
      <div class="content">
        <!-- 面包屑导航 -->
        <div class="breadcrumb">
          <el-breadcrumb separator="/">
            <el-breadcrumb-item 
              v-for="(item, index) in breadcrumbItems" 
              :key="index"
              @click="handleBreadcrumbClick(item)"
              :class="{ 'clickable': index < breadcrumbItems.length - 1 }"
            >
              {{ item.name }}
            </el-breadcrumb-item>
          </el-breadcrumb>
        </div>

        <!-- 文件列表 -->
        <div class="file-list">
          <FileList
            :files="fileList"
            :folders="folderList"
            :loading="loading"
            :current-folder-id="currentFolderIdSafe"
            @file-select="handleFileSelect"
            @file-double-click="handleFileDoubleClick"
            @file-context-menu="handleFileContextMenu"
            @folder-double-click="handleFolderDoubleClick"
            @selection-change="handleSelectionChange"
            @file-download="downloadFile"
          />
        </div>

        <!-- 分页 -->
        <div class="pagination">
          <el-pagination
            v-model:current-page="pagination.pageNum"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>

    <!-- 文件上传对话框 -->
    <FileUploadDialog
      v-model:visible="uploadDialogVisible"
      :folder-id="currentFolderIdSafe"
      @upload-success="handleUploadSuccess"
    />

    <!-- 新建文件夹对话框 -->
    <CreateFolderDialog
      v-model:visible="createFolderDialogVisible"
      :parent-id="currentFolderIdSafe"
      :folder-tree="folderTree"
      @create-success="handleCreateFolderSuccess"
    />

    <!-- 文件预览对话框 -->
    <FilePreviewDialog
      v-model:visible="previewDialogVisible"
      :file="selectedFile"
      @download="handlePreviewDownload"
      @share="handlePreviewShare"
    />

    <!-- 分享对话框 -->
    <ShareDialog
      v-model:visible="shareDialogVisible"
      :resource="selectedResource"
      @share-success="handleShareSuccess"
    />

    <!-- 权限设置对话框 -->
    <PermissionDialog
      v-model:visible="permissionDialogVisible"
      :resource="selectedResource"
      @permission-success="handlePermissionSuccess"
    />

    <!-- 右键菜单 -->
    <ContextMenu
      v-model:visible="contextMenuVisible"
      :position="contextMenuPosition"
    :items="contextMenuItems"
    @item-click="handleContextMenuClick"
  />
  
  <!-- 文件夹选择对话框 -->
  <FolderSelectDialog
    :visible="folderSelectDialogVisible"
    :title="folderSelectTitle"
    :excludeFolderId="excludeFolderId"
    @update:visible="folderSelectDialogVisible = $event"
    @confirm="handleFolderSelectConfirm"
  />

  <!-- 个人存储统计 -->
  <div class="storage-stats-bar">
    <el-row :gutter="16">
      <el-col :span="6">
        <el-card shadow="never" class="stat-mini-card">
          <div class="stat-mini-content">
            <el-icon class="stat-mini-icon"><Document /></el-icon>
            <div class="stat-mini-info">
              <div class="stat-mini-value">{{ storageStats.totalSizeFormatted }}</div>
              <div class="stat-mini-label">总空间</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="never" class="stat-mini-card">
          <div class="stat-mini-content">
            <el-icon class="stat-mini-icon"><Folder /></el-icon>
            <div class="stat-mini-info">
              <div class="stat-mini-value">{{ storageStats.usedSizeFormatted }}</div>
              <div class="stat-mini-label">已使用</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="never" class="stat-mini-card">
          <div class="stat-mini-content">
            <el-icon class="stat-mini-icon"><Files /></el-icon>
            <div class="stat-mini-info">
              <div class="stat-mini-value">{{ storageStats.fileCount }}</div>
              <div class="stat-mini-label">文件数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="never" class="stat-mini-card">
          <div class="stat-mini-content">
            <el-icon class="stat-mini-icon"><FolderOpened /></el-icon>
            <div class="stat-mini-info">
              <div class="stat-mini-value">{{ storageStats.folderCount }}</div>
              <div class="stat-mini-label">文件夹</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <div class="usage-indicator">
      <el-progress
        :percentage="storageStats.usagePercentage"
        :stroke-width="8"
        :show-text="false"
      />
      <span class="percentage-text">{{ storageStats.usagePercentage }}%</span>
    </div>
  </div>
</div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserStore } from '@/store/modules/user'
import {
  Upload,
  FolderAdd,
  Refresh,
  Search,
  ArrowRight,
  ArrowLeft,
  Document,
  Folder,
  Files,
  FolderOpened
} from '@element-plus/icons-vue'

import { fileApi, folderApi, storageApi, type FileQuery, type FolderQuery } from '@/api/cd'
import type { CdFileVo, CdFolderVo, FileSelectionItem } from '@/types/cd'

// 组件导入
import FolderTree from './components/FolderTree.vue'
import FileList from './components/FileList.vue'
import FileUploadDialog from './components/FileUploadDialog.vue'
import CreateFolderDialog from './components/CreateFolderDialog.vue'
import FilePreviewDialog from './components/FilePreviewDialog.vue'
import ShareDialog from './components/ShareDialog.vue'
import PermissionDialog from './components/PermissionDialog.vue'
import ContextMenu from './components/ContextMenu.vue'
import FolderSelectDialog from './components/FolderSelectDialog.vue'

// 用户store
const userStore = useUserStore()

// 响应式数据
const loading = ref(false)
const sidebarCollapsed = ref(false)
const searchKeyword = ref('')
const currentFolderId = ref<number | string | null>(null) // 初始化为null，表示未选中文件夹
const selectedFiles = ref<CdFileVo[]>([])
const selectedFolders = ref<CdFolderVo[]>([])

// 计算属性：提供非null的folderId，用于组件传递
const currentFolderIdSafe = computed(() => currentFolderId.value || 0)

// 数据列表
const fileList = ref<CdFileVo[]>([])
const folderList = ref<CdFolderVo[]>([])
const folderTree = ref<CdFolderVo[]>([])

// 存储统计
const storageStats = reactive({
  totalSize: 0,
  usedSize: 0,
  fileCount: 0,
  folderCount: 0,
  totalSizeFormatted: '0 B',
  usedSizeFormatted: '0 B',
  usagePercentage: 0
})

// 分页
const pagination = reactive({
  pageNum: 1,
  pageSize: 20,
  total: 0
})

// 对话框状态
const uploadDialogVisible = ref(false)
const createFolderDialogVisible = ref(false)
const previewDialogVisible = ref(false)
const shareDialogVisible = ref(false)
const permissionDialogVisible = ref(false)

// 选中的资源
const selectedFile = ref<CdFileVo | null>(null)
const selectedResource = ref<{ type: string; id: number | string; name: string } | null>(null)

// 右键菜单
const contextMenuVisible = ref(false)
const contextMenuPosition = ref({ x: 0, y: 0 })
const contextMenuItems = ref<Array<{ label: string; icon?: string; disabled?: boolean }>>([])

// 文件夹选择对话框
const folderSelectDialogVisible = ref(false)
const folderSelectTitle = ref('')
const excludeFolderId = ref<number | string | undefined>()
const pendingOperation = ref<{ type: 'move' | 'copy'; resourceType: 'file' | 'folder'; source: { id: number | string; name: string } } | null>(null)

// 面包屑导航
const breadcrumbItems = computed(() => {
  const items = [{ id: 0, name: '我的文件' }]
  // TODO: 根据当前文件夹路径构建面包屑
  return items
})

// 生命周期
onMounted(async () => {
  await loadFolderTree()
  // 尝试选中根文件夹
  await selectRootFolder()
  await loadFileList()
  await loadStorageStats()
})

// 方法
const loadFolderTree = async () => {
  try {
    // 获取当前用户ID，这里应该从登录信息中获取
    // 暂时使用1作为示例，实际应该从store或token中获取
    const currentUserId = 1 // TODO: 从用户store获取实际用户ID
    console.log('开始加载文件夹树，用户ID:', currentUserId)
    
    const response = await folderApi.getTree(currentUserId)
    console.log('文件夹树API响应:', response)
    console.log('文件夹树API响应类型:', typeof response)
    console.log('文件夹树API响应结构:', Object.keys(response))
    console.log('文件夹树数据:', response.data)
    console.log('文件夹树数据类型:', typeof response.data)
    console.log('文件夹树数据长度:', response.data?.length)
    
    folderTree.value = response.data
    console.log('设置后的folderTree:', folderTree.value)
    console.log('设置后的folderTree长度:', folderTree.value?.length)
    console.log('设置后的folderTree类型:', typeof folderTree.value)
  } catch (error) {
    console.error('加载文件夹树失败:', error);
    ElMessage.error('加载文件夹树失败')
  }
}

// 选中根文件夹
const selectRootFolder = async () => {
  try {
    const currentUserId = userStore.userId
    console.log('开始选中根文件夹，用户ID:', currentUserId)
    const rootFolderResponse = await folderApi.getUserRoot(currentUserId)
    if (rootFolderResponse.data && rootFolderResponse.data.folderId) {
      currentFolderId.value = rootFolderResponse.data.folderId
      console.log('根文件夹选中成功，folderId:', currentFolderId.value)
    } else {
      // 如果获取不到根文件夹，尝试使用文件夹树的第一个
      if (folderTree.value && folderTree.value.length > 0) {
        currentFolderId.value = folderTree.value[0].folderId
        console.log('使用文件夹树第一个文件夹，folderId:', currentFolderId.value)
      }
    }
  } catch (error) {
    console.error('选中根文件夹失败:', error)
  }
}

const loadFileList = async () => {
  loading.value = true
  try {
    // 如果是根目录（currentFolderId = 0），需要先获取用户根文件夹ID
    let actualFolderId = currentFolderId.value
    if (actualFolderId === 0) {
      // 获取用户根文件夹
      const currentUserId = userStore.userId
      console.log('当前用户ID:', currentUserId)
      const rootFolderResponse = await folderApi.getUserRoot(currentUserId)
      if (rootFolderResponse.data && rootFolderResponse.data.folderId) {
        actualFolderId = rootFolderResponse.data.folderId
      }
    }
    
    const fileParams: FileQuery = {
      folderId: actualFolderId as number,
      pageNum: pagination.pageNum,
      pageSize: pagination.pageSize
    }
    
    const folderParams: FolderQuery = {
      parentId: actualFolderId as number,
      pageNum: pagination.pageNum,
      pageSize: pagination.pageSize
    }
    
    const [fileResponse, folderResponse] = await Promise.all([
      fileApi.list(fileParams),
      folderApi.list(folderParams)
    ])
    
    // 适配后端返回的数据结构
    fileList.value = fileResponse.data || []
    folderList.value = folderResponse.data || []
    pagination.total = (fileResponse.data || []).length
  } catch (error) {
    console.error('加载文件列表失败:', error)
    ElMessage.error('加载文件列表失败')
  } finally {
    loading.value = false
  }
}

const handleUpload = () => {
  // 检查是否选中了文件夹（0代表根文件夹，也为有效值）
  if (currentFolderId.value === null || currentFolderId.value === undefined || currentFolderId.value === '') {
    ElMessage.warning('请先选中要上传文件的文件夹')
    return
  }
  // 如果值为0，说明在根文件夹，允许上传
  uploadDialogVisible.value = true
}

const handleCreateFolder = () => {
  // 检查是否选中了文件夹（0代表根文件夹，也为有效值）
  if (currentFolderId.value === null || currentFolderId.value === undefined || currentFolderId.value === '') {
    ElMessage.warning('请先选中要创建文件夹的父文件夹')
    return
  }
  // 如果值为0，说明在根文件夹，允许创建
  createFolderDialogVisible.value = true
}

const handleRefresh = () => {
  loadFileList()
  loadFolderTree()
  loadStorageStats()
}

// 加载存储统计
const loadStorageStats = async () => {
  try {
    const response = await storageApi.getUserStorage()
    if (response.data) {
      const data = response.data
      storageStats.totalSize = data.totalSize || 0
      storageStats.usedSize = data.usedSize || 0
      storageStats.fileCount = data.fileCount || 0
      storageStats.folderCount = data.folderCount || 0
      storageStats.totalSizeFormatted = formatSize(data.totalSize || 0)
      storageStats.usedSizeFormatted = formatSize(data.usedSize || 0)
      storageStats.usagePercentage = data.totalSize > 0 
        ? Math.round((data.usedSize / data.totalSize) * 100) 
        : 0
    }
  } catch (error) {
    console.error('加载存储统计失败:', error)
  }
}

// 格式化文件大小
const formatSize = (bytes: number): string => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

const handleSearch = async () => {
  if (!searchKeyword.value.trim()) {
    loadFileList()
    return
  }
  
  loading.value = true
  try {
    const params = {
      keyword: searchKeyword.value,
      pageNum: pagination.pageNum,
      pageSize: pagination.pageSize
    }
    
    const response = await fileApi.search(params)
    fileList.value = response.data.rows || []
    folderList.value = []
    pagination.total = response.data.total || 0
  } catch (error) {
    console.error('搜索失败:', error)
    ElMessage.error('搜索失败')
  } finally {
    loading.value = false
  }
}

const handleFolderSelect = (folderId: number | string) => {
  currentFolderId.value = folderId
  pagination.pageNum = 1
  loadFileList()
}

const handleFileSelect = (file: CdFileVo) => {
  selectedFile.value = file
}

const handleFileDoubleClick = (file: CdFileVo) => {
  if (file.canPreview) {
    selectedFile.value = file
    previewDialogVisible.value = true
  } else {
    // 下载文件
    downloadFile(file)
  }
}

const handleFolderDoubleClick = (folder: CdFolderVo) => {
  handleFolderSelect(folder.folderId)
}

const handleSelectionChange = (files: CdFileVo[], folders: CdFolderVo[]) => {
  selectedFiles.value = files
  selectedFolders.value = folders
}

const handleBreadcrumbClick = (item: { id: number; name: string }) => {
  handleFolderSelect(item.id)
}

const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  pagination.pageNum = 1
  loadFileList()
}

const handleCurrentChange = (page: number) => {
  pagination.pageNum = page
  loadFileList()
}

const toggleSidebar = () => {
  sidebarCollapsed.value = !sidebarCollapsed.value
}

// 右键菜单处理
const handleFileContextMenu = (file: CdFileVo, event: MouseEvent) => {
  event.preventDefault()
  contextMenuPosition.value = { x: event.clientX, y: event.clientY }
  
  console.log('右键文件:', file)
  console.log('文件ID:', file.fileId)
  console.log('文件ID类型:', typeof file.fileId)
  
  contextMenuItems.value = [
    { label: '下载', icon: 'Download' },
    { label: '重命名', icon: 'Edit' },
    { label: '移动', icon: 'Move' },
    { label: '复制', icon: 'CopyDocument' },
    { label: '分享', icon: 'Share' },
    { label: '权限设置', icon: 'Key' },
    { label: '删除', icon: 'Delete', disabled: false }
  ]
  
  selectedFile.value = file
  contextMenuVisible.value = true
}

const handleFolderContextMenu = (folder: CdFolderVo, event: MouseEvent) => {
  event.preventDefault()
  contextMenuPosition.value = { x: event.clientX, y: event.clientY }
  
  contextMenuItems.value = [
    { label: '上传文件', icon: 'Upload' },
    { label: '重命名', icon: 'Edit' },
    { label: '移动', icon: 'Move' },
    { label: '复制', icon: 'CopyDocument' },
    { label: '分享', icon: 'Share' },
    { label: '权限设置', icon: 'Key' },
    { label: '删除', icon: 'Delete', disabled: folder.folderId === 0 }
  ]
  
  selectedResource.value = {
    type: 'folder',
    id: folder.folderId,
    name: folder.folderName
  }
  contextMenuVisible.value = true
}

const handleContextMenuClick = async (item: { label: string }) => {
  contextMenuVisible.value = false
  
  switch (item.label) {
    case '下载':
      if (selectedFile.value) {
        downloadFile(selectedFile.value)
      }
      break
    case '重命名':
      if (selectedFile.value) {
        renameFile(selectedFile.value)
      } else if (selectedResource.value) {
        renameFolder(selectedResource.value)
      }
      break
    case '移动':
      if (selectedFile.value) {
        moveFile(selectedFile.value)
      } else if (selectedResource.value) {
        moveFolder(selectedResource.value)
      }
      break
    case '复制':
      if (selectedFile.value) {
        copyFile(selectedFile.value)
      } else if (selectedResource.value) {
        copyFolder(selectedResource.value)
      }
      break
    case '分享':
      if (selectedFile.value) {
        selectedResource.value = {
          type: 'file',
          id: selectedFile.value.fileId,
          name: selectedFile.value.originalName
        }
      }
      shareDialogVisible.value = true
      break
    case '权限设置':
      if (selectedFile.value) {
        selectedResource.value = {
          type: 'file',
          id: selectedFile.value.fileId,
          name: selectedFile.value.originalName
        }
      }
      permissionDialogVisible.value = true
      break
    case '上传文件':
      if (selectedResource.value) {
        // 切换到选中的文件夹，然后打开上传对话框
        currentFolderId.value = selectedResource.value.id
        uploadDialogVisible.value = true
      }
      break
    case '删除':
      if (selectedFile.value) {
        deleteFile(selectedFile.value)
      } else if (selectedResource.value) {
        deleteFolder(selectedResource.value)
      }
      break
  }
}

// 文件操作
const downloadFile = async (file: CdFileVo) => {
  try {
    const blob = await fileApi.download(file.fileId) as any as Blob
    // 处理文件下载
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = file.originalName || 'download'
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
    ElMessage.success('文件下载成功')
  } catch (error) {
    console.error('下载文件失败:', error)
    ElMessage.error('下载文件失败')
  }
}

const renameFile = async (file: CdFileVo) => {
  try {
    const { value: newName } = await ElMessageBox.prompt('请输入新文件名', '重命名', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputValue: file.originalName,
      inputValidator: (value) => {
        if (!value || !value.trim()) {
          return '文件名不能为空'
        }
        return true
      }
    })
    
    await fileApi.rename(file.fileId, newName)
    ElMessage.success('重命名成功')
    loadFileList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('重命名文件失败:', error)
      ElMessage.error('重命名文件失败')
    }
  }
}

const renameFolder = async (resource: { id: number | string; name: string }) => {
  try {
    const { value: newName } = await ElMessageBox.prompt('请输入新文件夹名', '重命名', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputValue: resource.name,
      inputValidator: (value) => {
        if (!value || !value.trim()) {
          return '文件夹名不能为空'
        }
        return true
      }
    })
    
    await folderApi.rename(resource.id as any, newName)
    ElMessage.success('重命名成功')
    loadFileList()
    loadFolderTree()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('重命名文件夹失败:', error)
      ElMessage.error('重命名文件夹失败')
    }
  }
}

const moveFile = async (file: CdFileVo) => {
  console.log('准备移动文件:', file)
  pendingOperation.value = {
    type: 'move',
    resourceType: 'file',
    source: { id: file.fileId, name: file.originalName }
  }
  folderSelectTitle.value = '选择目标文件夹'
  excludeFolderId.value = undefined
  folderSelectDialogVisible.value = true
}

const moveFolder = async (resource: { id: number | string; name: string }) => {
  pendingOperation.value = {
    type: 'move',
    resourceType: 'folder',
    source: resource
  }
  folderSelectTitle.value = '选择目标文件夹'
  excludeFolderId.value = resource.id
  folderSelectDialogVisible.value = true
}

const copyFile = async (file: CdFileVo) => {
  pendingOperation.value = {
    type: 'copy',
    resourceType: 'file',
    source: { id: file.fileId, name: file.originalName }
  }
  folderSelectTitle.value = '选择目标文件夹'
  excludeFolderId.value = undefined
  folderSelectDialogVisible.value = true
}

const copyFolder = async (resource: { id: number | string; name: string }) => {
  pendingOperation.value = {
    type: 'copy',
    resourceType: 'folder',
    source: resource
  }
  folderSelectTitle.value = '选择目标文件夹'
  excludeFolderId.value = resource.id
  folderSelectDialogVisible.value = true
}

const deleteFile = async (file: CdFileVo) => {
  try {
    await ElMessageBox.confirm(`确定要删除文件 "${file.originalName}" 吗？`, '删除确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await fileApi.delete([file.fileId])
    ElMessage.success('删除成功')
    loadFileList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除文件失败:', error)
      ElMessage.error('删除文件失败')
    }
  }
}

const deleteFolder = async (resource: { id: number | string; name: string }) => {
  try {
    await ElMessageBox.confirm(`确定要删除文件夹 "${resource.name}" 吗？`, '删除确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    console.log('删除文件夹，ID:', resource.id, '类型:', typeof resource.id)
    await folderApi.delete([resource.id])
    ElMessage.success('删除成功')
    
    // 如果删除的是当前文件夹，需要切换到父文件夹或根目录
    if (currentFolderId.value === resource.id) {
      // 这里需要获取父文件夹ID，暂时重置为根目录
      currentFolderId.value = 0
    }
    
    loadFileList()
    loadFolderTree()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除文件夹失败:', error)
      ElMessage.error('删除文件夹失败')
    }
  }
}

// 事件处理
const handleUploadSuccess = () => {
  loadFileList()
  loadFolderTree()
}

const handleCreateFolderSuccess = () => {
  loadFileList()
  loadFolderTree()
}

const handleShareSuccess = () => {
  // 子组件 ShareDialog 已显示成功提示，这里不需要重复提示
}

const handlePermissionSuccess = () => {
  // 子组件会显示成功提示，这里不需要重复提示
}

const handlePreviewDownload = (file: CdFileVo) => {
  // 预览对话框的下载，实际已在组件内部处理
  // 这里可以添加额外的逻辑，比如记录下载日志等
  console.log('预览对话框下载文件:', file.originalName)
}

const handlePreviewShare = (file: CdFileVo) => {
  // 打开分享对话框
  selectedResource.value = {
    type: 'file',
    id: file.fileId,
    name: file.originalName
  }
  shareDialogVisible.value = true
}

const handleFolderSelectConfirm = async (folderId: number | string) => {
  if (!pendingOperation.value) return
  
  try {
    const { type, resourceType, source } = pendingOperation.value
    
    console.log('执行操作:', { type, resourceType, sourceId: source.id, targetFolderId: folderId, targetFolderIdType: typeof folderId })
    
    // 确保ID是BigInt或Long，JavaScript的Number最大安全整数是2^53-1
    const sourceIdBigInt = typeof source.id === 'string' ? BigInt(source.id) : source.id
    
    if (type === 'move') {
      if (resourceType === 'file') {
        console.log('移动文件:', source.id, '到文件夹:', folderId)
        await fileApi.move(source.id as any, folderId as any)
        ElMessage.success('文件移动成功')
      } else {
        console.log('移动文件夹:', source.id, '到文件夹:', folderId)
        await folderApi.move(source.id as any, folderId as any)
        ElMessage.success('文件夹移动成功')
      }
    } else if (type === 'copy') {
      if (resourceType === 'file') {
        console.log('复制文件:', source.id, '到文件夹:', folderId)
        await fileApi.copy(source.id as any, folderId as any)
        ElMessage.success('文件复制成功')
      } else {
        console.log('复制文件夹:', source.id, '到文件夹:', folderId)
        await folderApi.copy(source.id as any, folderId as any)
        ElMessage.success('文件夹复制成功')
      }
    }
    
    loadFileList()
    loadFolderTree()
    pendingOperation.value = null
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error('操作失败')
  }
}
</script>

<style scoped lang="scss">
.cloud-drive-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f5f5f5;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 24px;
  background: white;
  border-bottom: 1px solid #e4e7ed;
  
  .toolbar-left {
    display: flex;
    gap: 12px;
  }
  
  .toolbar-right {
    display: flex;
    gap: 12px;
    align-items: center;
  }
}

.main-content {
  flex: 1;
  display: flex;
  overflow: hidden;
}

.sidebar {
  width: 280px;
  background: white;
  border-right: 1px solid #e4e7ed;
  display: flex;
  flex-direction: column;
  
  .sidebar-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px 20px;
    border-bottom: 1px solid #e4e7ed;
    
    h3 {
      margin: 0;
      font-size: 16px;
      font-weight: 500;
    }
  }
  
  .sidebar-content {
    flex: 1;
    overflow-y: auto;
  }
}

.content {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: white;
  overflow: hidden;
}

.breadcrumb {
  padding: 16px 24px;
  border-bottom: 1px solid #e4e7ed;
  
  .clickable {
    cursor: pointer;
    color: #409eff;
    
    &:hover {
      text-decoration: underline;
    }
  }
}

.file-list {
  flex: 1;
  overflow-y: auto;
  padding: 0 24px;
}

.pagination {
  padding: 16px 24px;
  border-top: 1px solid #e4e7ed;
  display: flex;
  justify-content: center;
}

.storage-stats-bar {
  margin: 16px 24px;
  
  .stat-mini-card {
    margin-bottom: 8px;
    
    :deep(.el-card__body) {
      padding: 12px;
    }
    
    .stat-mini-content {
      display: flex;
      align-items: center;
      
      .stat-mini-icon {
        font-size: 24px;
        color: #409eff;
        margin-right: 12px;
      }
      
      .stat-mini-info {
        flex: 1;
        
        .stat-mini-value {
          font-size: 18px;
          font-weight: 500;
          color: #303133;
          margin-bottom: 4px;
        }
        
        .stat-mini-label {
          font-size: 12px;
          color: #909399;
        }
      }
    }
  }
  
  .usage-indicator {
    display: flex;
    align-items: center;
    gap: 12px;
    margin-top: 8px;
    
    .el-progress {
      flex: 1;
    }
    
    .percentage-text {
      font-size: 14px;
      font-weight: 500;
      color: #303133;
      min-width: 40px;
    }
  }
}
</style>
